<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <div class="task-collaboration-container">
        <!-- 任务基本信息 -->
        <div class="task-info-section">
          <h3>任务信息</h3>
          <a-descriptions :column="3" bordered size="small">
            <a-descriptions-item label="任务名称">{{ taskInfo.taskName }}</a-descriptions-item>
            <a-descriptions-item label="工种">{{ taskInfo.workTypeName }}</a-descriptions-item>
            <a-descriptions-item label="任务数量">{{ taskInfo.taskQuantity }}</a-descriptions-item>
            <a-descriptions-item label="协作类型">{{ getCollaborationTypeText(taskInfo.collaborationType) }}</a-descriptions-item>
            <a-descriptions-item label="最大参与人数">{{ taskInfo.maxParticipants }}</a-descriptions-item>
            <a-descriptions-item label="允许部分领取">{{ taskInfo.allowPartialClaim ? '是' : '否' }}</a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- 参与者管理 -->
        <div class="participants-section">
          <div class="section-header">
            <h3>参与者管理</h3>
            <a-button type="primary" @click="showAddParticipant" :disabled="!canAddParticipant">
              <a-icon type="plus" />
              添加参与者
            </a-button>
          </div>
          <a-table
            :columns="participantColumns"
            :dataSource="participants"
            :pagination="false"
            size="small"
            rowKey="id"
          >
  <template slot="employeeName" slot-scope="text, record">
    <span>{{ record.employeeName }}</span>
    <a-tag v-if="record.isLeader" color="gold" style="margin-left: 8px">负责人</a-tag>
  </template>
  
  <template slot="claimQuantity" slot-scope="text, record">
    <a-input-number
      v-model="record.claimQuantity"
      :min="1"
      :max="getMaxClaimQuantity(record)"
      :disabled="record.status !== 'claimed'"
      @change="onClaimQuantityChange(record)"
      style="width: 100px"
    />
  </template>
  
  <template slot="participationRatio" slot-scope="text, record">
    <span>{{ (record.participationRatio * 100).toFixed(1) }}%</span>
  </template>
  
  <template slot="status" slot-scope="text, record">
    <a-tag :color="getStatusColor(record.status)">
      {{ getStatusText(record.status) }}
    </a-tag>
  </template>
  
  <template slot="action" slot-scope="text, record">
    <a-button-group size="small">
      <a-button 
        v-if="record.status === 'claimed'" 
        type="primary" 
        @click="startTask(record)"
      >
        开始
      </a-button>
      <a-button 
        v-if="record.status === 'in_progress'" 
        @click="pauseTask(record)"
      >
        暂停
      </a-button>
      <a-button 
        v-if="record.status === 'paused'" 
        type="primary" 
        @click="resumeTask(record)"
      >
        恢复
      </a-button>
      <a-button 
        v-if="['claimed', 'in_progress', 'paused'].includes(record.status)" 
        type="danger" 
        @click="removeParticipant(record)"
      >
        移除
      </a-button>
    </a-button-group>
  </template>
</a-table>
        </div>

        <!-- 进度统计 -->
        <div class="progress-section">
<h3>进度统计</h3>
<a-row :gutter="16">
  <a-col :span="6">
    <a-statistic title="总任务量" :value="taskInfo.taskQuantity" suffix="件" />
  </a-col>
  <a-col :span="6">
    <a-statistic title="已领取" :value="totalClaimedQuantity" suffix="件" />
  </a-col>
  <a-col :span="6">
    <a-statistic title="已完成" :value="totalCompletedQuantity" suffix="件" />
  </a-col>
  <a-col :span="6">
    <a-statistic 
      title="完成率" 
      :value="completionRate" 
      suffix="%" 
      :precision="1"
    />
  </a-col>
</a-row>
<div style="margin-top: 16px">
  <a-progress 
    :percent="completionRate" 
    :status="completionRate === 100 ? 'success' : 'active'"
  />
</div>
        </div>
      </div>
    </a-spin>

    <!-- 添加参与者模态框 -->
    <a-modal
      title="添加参与者"
      :visible="addParticipantVisible"
      :confirmLoading="addParticipantLoading"
      @ok="handleAddParticipant"
      @cancel="handleCancelAddParticipant"
      width="800px"
    >
      <div class="add-participant-form">
        <a-form-model :model="addParticipantForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
<a-form-model-item label="选择员工">
  <a-select
    v-model="addParticipantForm.employeeId"
    placeholder="请选择员工"
    show-search
    :filter-option="filterEmployee"
    @change="onEmployeeChange"
  >
    <a-select-option 
      v-for="employee in availableEmployees" 
      :key="employee.id" 
      :value="employee.id"
    >
      {{ employee.employeeName }} - {{ employee.departmentName }}
    </a-select-option>
  </a-select>
</a-form-model-item>
<a-form-model-item label="领取数量">
  <a-input-number
    v-model="addParticipantForm.claimQuantity"
    :min="1"
    :max="remainingQuantity"
    placeholder="请输入领取数量"
    style="width: 200px"
  />
  <span style="margin-left: 8px; color: #666">
    剩余可领取: {{ remainingQuantity }} 件
  </span>
</a-form-model-item>
<a-form-model-item label="设为负责人">
  <a-switch v-model="addParticipantForm.isLeader" />
  <span style="margin-left: 8px; color: #666">
    负责人负责协调任务进度
  </span>
</a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'

export default {
  name: 'TaskCollaborationModal',
  data() {
    return {
      title: '任务协作管理',
      visible: false,
      confirmLoading: false,
      taskInfo: {},
      participants: [],
      availableEmployees: [],
      addParticipantVisible: false,
      addParticipantLoading: false,
      addParticipantForm: {
        employeeId: undefined,
        claimQuantity: 1,
        isLeader: false
      },
      participantColumns: [
        {
title: '员工姓名',
dataIndex: 'employeeName',
width: 150,
scopedSlots: { customRender: 'employeeName' }
        },
        {
title: '部门',
dataIndex: 'departmentName',
width: 120
        },
        {
title: '领取数量',
dataIndex: 'claimQuantity',
width: 120,
scopedSlots: { customRender: 'claimQuantity' }
        },
        {
title: '完成数量',
dataIndex: 'completedQuantity',
width: 100
        },
        {
title: '参与比例',
dataIndex: 'participationRatio',
width: 100,
scopedSlots: { customRender: 'participationRatio' }
        },
        {
title: '状态',
dataIndex: 'status',
width: 100,
scopedSlots: { customRender: 'status' }
        },
        {
title: '开始时间',
dataIndex: 'startTime',
width: 150
        },
        {
title: '操作',
dataIndex: 'action',
width: 200,
scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        getTaskParticipants: '/mes/taskParticipant/getByTaskId',
        addParticipant: '/mes/taskParticipant/add',
        updateParticipant: '/mes/taskParticipant/update',
        removeParticipant: '/mes/taskParticipant/remove',
        startTask: '/mes/taskParticipant/start',
        pauseTask: '/mes/taskParticipant/pause',
        resumeTask: '/mes/taskParticipant/resume',
        getAvailableEmployees: '/mes/employee/getAvailableForTask'
      }
    }
  },
  computed: {
    totalClaimedQuantity() {
      return this.participants.reduce((sum, p) => sum + (p.claimQuantity || 0), 0)
    },
    totalCompletedQuantity() {
      return this.participants.reduce((sum, p) => sum + (p.completedQuantity || 0), 0)
    },
    completionRate() {
      if (!this.taskInfo.taskQuantity) return 0
      return (this.totalCompletedQuantity / this.taskInfo.taskQuantity) * 100
    },
    remainingQuantity() {
      return (this.taskInfo.taskQuantity || 0) - this.totalClaimedQuantity
    },
    canAddParticipant() {
      const maxReached = this.participants.length >= (this.taskInfo.maxParticipants || 999)
      const quantityFull = this.remainingQuantity <= 0
      return !maxReached && !quantityFull
    }
  },
  methods: {
    show(taskInfo) {
      this.visible = true
      this.taskInfo = Object.assign({}, taskInfo)
      this.loadTaskParticipants()
      this.loadAvailableEmployees()
    },
    close() {
      this.visible = false
      this.participants = []
      this.taskInfo = {}
    },
    handleOk() {
      this.$emit('ok')
      this.close()
    },
    handleCancel() {
      this.close()
    },
    loadTaskParticipants() {
      this.confirmLoading = true
      getAction(this.url.getTaskParticipants, { taskId: this.taskInfo.id })
        .then(res => {
if (res.success) {
  this.participants = res.result || []
  this.calculateParticipationRatios()
}
        })
        .finally(() => {
this.confirmLoading = false
        })
    },
    loadAvailableEmployees() {
      getAction(this.url.getAvailableEmployees, { 
        workTypeId: this.taskInfo.workTypeId 
      }).then(res => {
        if (res.success) {
this.availableEmployees = res.result || []
        }
      })
    },
    calculateParticipationRatios() {
      const totalClaimed = this.totalClaimedQuantity
      if (totalClaimed > 0) {
        this.participants.forEach(p => {
p.participationRatio = (p.claimQuantity || 0) / totalClaimed
        })
      }
    },
    showAddParticipant() {
      this.addParticipantVisible = true
      this.addParticipantForm = {
        employeeId: undefined,
        claimQuantity: Math.min(this.remainingQuantity, 1),
        isLeader: false
      }
    },
    handleAddParticipant() {
      if (!this.addParticipantForm.employeeId) {
        this.$message.warning('请选择员工')
        return
      }
      if (!this.addParticipantForm.claimQuantity || this.addParticipantForm.claimQuantity <= 0) {
        this.$message.warning('请输入有效的领取数量')
        return
      }

      this.addParticipantLoading = true
      const formData = {
        taskId: this.taskInfo.id,
        employeeId: this.addParticipantForm.employeeId,
        claimQuantity: this.addParticipantForm.claimQuantity,
        isLeader: this.addParticipantForm.isLeader
      }

      httpAction(this.url.addParticipant, formData, 'post')
        .then(res => {
if (res.success) {
  this.$message.success('添加参与者成功')
  this.addParticipantVisible = false
  this.loadTaskParticipants()
} else {
  this.$message.warning(res.message)
}
        })
        .finally(() => {
this.addParticipantLoading = false
        })
    },
    handleCancelAddParticipant() {
      this.addParticipantVisible = false
    },
    onEmployeeChange(employeeId) {
      // 可以在这里根据员工信息调整默认领取数量等
    },
    filterEmployee(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    onClaimQuantityChange(record) {
      // 实时更新参与比例
      this.calculateParticipationRatios()
      
      // 可以考虑实时保存到后端
      this.updateParticipant(record)
    },
    updateParticipant(record) {
      const formData = {
        id: record.id,
        claimQuantity: record.claimQuantity
      }
      
      httpAction(this.url.updateParticipant, formData, 'put')
        .then(res => {
if (res.success) {
  this.$message.success('更新成功')
}
        })
    },
    startTask(record) {
      httpAction(this.url.startTask, { id: record.id }, 'post')
        .then(res => {
if (res.success) {
  this.$message.success('任务已开始')
  this.loadTaskParticipants()
}
        })
    },
    pauseTask(record) {
      httpAction(this.url.pauseTask, { id: record.id }, 'post')
        .then(res => {
if (res.success) {
  this.$message.success('任务已暂停')
  this.loadTaskParticipants()
}
        })
    },
    resumeTask(record) {
      httpAction(this.url.resumeTask, { id: record.id }, 'post')
        .then(res => {
if (res.success) {
  this.$message.success('任务已恢复')
  this.loadTaskParticipants()
}
        })
    },
    removeParticipant(record) {
      this.$confirm({
        title: '确认移除',
        content: `确定要移除参与者 ${record.employeeName} 吗？`,
        onOk: () => {
httpAction(this.url.removeParticipant, { id: record.id }, 'delete')
  .then(res => {
    if (res.success) {
      this.$message.success('移除成功')
      this.loadTaskParticipants()
    }
  })
        }
      })
    },
    getMaxClaimQuantity(record) {
      return record.claimQuantity + this.remainingQuantity
    },
    getCollaborationTypeText(type) {
      const typeMap = {
        'independent': '独立完成',
        'collaborative': '协作完成',
        'segmented': '分段完成'
      }
      return typeMap[type] || type
    },
    getStatusColor(status) {
      const colorMap = {
        'claimed': 'blue',
        'in_progress': 'processing',
        'paused': 'warning',
        'completed': 'success'
      }
      return colorMap[status] || 'default'
    },
    getStatusText(status) {
      const textMap = {
        'claimed': '已领取',
        'in_progress': '进行中',
        'paused': '已暂停',
        'completed': '已完成'
      }
      return textMap[status] || status
    }
  }
}
</script>

<style scoped>
.task-collaboration-container {
  padding: 16px 0;
}

.task-info-section,
.participants-section,
.progress-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
}

.add-participant-form {
  padding: 16px 0;
}
</style>
